<template>
  <div>
    <el-row class="mt20">
      <el-col :span="4">
        <span class="transparent-text">123</span>
      </el-col>
      <el-col :span="12">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="编码">
            <el-input v-model="form.code" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="form.price" type="number" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.description" type="textarea" />
          </el-form-item>
          <el-form-item label="品牌">
            <el-select v-model="form.brandId" placeholder="请选择品牌">
              <el-option
                v-for="item in brandOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /></el-select>
          </el-form-item>
          <el-form-item label="分类">
            <div style="width: 30vw">
              <el-tree
                :data="categoryTreeData"
                :props="treeProps"
                :expand-on-click-node="false"
                :current-node-key="form.categoryId"
                :highlight-current="true"
                @node-click="categorySelect"
              />
            </div>
          </el-form-item>
          <el-form-item label="图片">
            <el-upload action="" class="avatar-uploader" :show-file-list="false" :before-upload="beforeUpload">
              <img v-if="form.introUrl" :src="form.introUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="onCancel">取消</el-button>
          </el-form-item>
        </el-form></el-col>
      <el-col :span="8" />
    </el-row>
  </div>
</template>

<script>
import { getAllBrandListApi } from "@/api/product/brand";
import { getCategoryTreeApi } from "@/api/product/category";
import { uploadFileApi, addProductApi, updateProductApi, getProductByIdApi } from "@/api/product/product";
export default {
  data() {
    return {
      form: {
        id: 0,
        code: "",
        name: "",
        price: "",
        categoryId: "",
        brandId: "",
        introUrl: "",
        description: "",
      },
      brandOptions: [],
      currentCategory: "",
      categoryTreeData: [],
      treeProps: {
        children: "children",
        label: "name",
      },
    };
  },
  mounted() {
    this.clearForm();
    this.form.id = this.$route.params.id;
    if (this.form.id === "0") {
      // 新增
    } else {
      // 编辑
      getProductByIdApi({ id: this.form.id }).then((res) => {
        if (res.code !== 200) {
          return this.$message.error("获取产品详情失败");
        }
        this.form = res.data;
      });
    }
    this.initBrandOptions();
    this.initCategoryTree();
  },
  methods: {
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error();
      }
      const formData = new FormData();
      formData.append("file", file);
      uploadFileApi(formData).then((res) => {
        if (res.code !== 200) {
          return this.$message.error("图片上传失败，请重试");
        }
        this.form.introUrl = res.data;
      });
      return false;
    },
    backToProductList() {
      this.$router.push("/product");
    },
    onCancel() {
      this.backToProductList();
    },
    onSubmit() {
      const params = {
        code: this.form.code,
        name: this.form.name,
        price: this.form.price,
        categoryId: this.form.categoryId,
        brandId: this.form.brandId,
        introUrl: this.form.introUrl,
        description: this.form.description,
      };
      // 先判断是新增还是编辑
      if (this.form.id === "0") {
        // 新增
        addProductApi(params).then((res) => {
          console.log("addProduct, res", res);
          if (res.code !== 200) {
            return this.$message.error("新增产品失败");
          }
          this.$message.success("新增产品成功");
          this.backToProductList();
        });
      } else {
        // 编辑
        params.id = this.form.id;
        updateProductApi(params).then((res) => {
          if (res.code !== 200) {
            return this.$message.error("更新产品失败");
          }
          this.$message.success("更新产品成功");
          this.backToProductList();
        });
      }
    },
    categorySelect(c) {
      this.form.categoryId = c.id;
    },
    initCategoryTree() {
      getCategoryTreeApi().then((res) => {
        if (res.code !== 200) {
          return this.$message.error("获取产品类别失败");
        }
        this.categoryTreeData = res.data[0].children;
      });
    },

    initBrandOptions() {
      getAllBrandListApi().then((res) => {
        // console.log("getBrandListPageApi, res", res);
        if (res.code !== 200) {
          return this.$message.error("获取品牌列表失败");
        }
        if (res.data && res.data.length > 0) {
          for (const b of res.data) {
            this.brandOptions.push({
              value: b.id,
              label: b.name,
            });
          }
          // console.log("this.brandOptions", this.brandOptions);
        }
      });
    },
    clearForm() {
      this.form = {
        id: 0,
        code: "",
        name: "",
        price: "",
        categoryId: "",
        brandId: "",
        introUrl: "",
        description: "",
      };
    },
  },
};
</script>

<style scoped>
.transparent-text {
  opacity: 0; /* 可以替换为0.0到1.0之间的任意值 */
}
.mt20 {
  margin-top: 20px;
}
</style>
